<template>
	<view>
    <view class="container">
      <uni-steps :active="currentStep" :options="steps" style="padding: 20rpx;"></uni-steps>
    </view>
    <view v-show="currentStep === 0">
      <view class="content" >
        <uni-section title="基本信息" type="line">
          <view class="example">
            <!-- 基础用法，不包含校验规则 -->
            <uni-forms ref="form" :modelValue="baseFormData" labelWidth="100px">
              <uni-forms-item label="事项标题" name="sxbt" >
                <uni-easyinput v-model="baseFormData.sxbt" disabled placeholder="请输入事项标题" />
              </uni-forms-item>
              <uni-forms-item label="事项性质" name="sxxz" >
                <uni-data-select v-model="baseFormData.sxxz" :localdata="sxxzDict" disabled
                                 @change="changeSxxzDict"></uni-data-select>
              </uni-forms-item>
              <uni-forms-item label="事项性质" name="sxlx" >
                <uni-data-select v-model="baseFormData.sxlx" :localdata="sxlxDict" disabled
                                 @change="changeSxlxDict"></uni-data-select>
              </uni-forms-item>
              <uni-forms-item label="紧急程度" name="jjcd" >
                <uni-data-checkbox v-model="baseFormData.jjcd" :localdata="jjcdDict" disabled
                                   @change="changeJjcdDict" />
              </uni-forms-item>
              <!-- <uni-forms-item label="间隔时间" name="jgsj"  v-if="baseFormData.jjcd === '2'">
                <uni-data-select v-model="baseFormData.jgsj" :localdata="jgsjDict" disabled
                  @change="changeJgsjDict"></uni-data-select>
              </uni-forms-item> -->
              <uni-forms-item label="是否反馈" name="sffk" >
                <uni-data-checkbox v-model="baseFormData.sffk" :localdata="sffkDict" disabled
                                   @change="changeSffkDict" />
              </uni-forms-item>
              <uni-forms-item label="截止日期" name="jzrq"  v-if="baseFormData.sffk === '1'">
                <uni-datetime-picker type="date" v-model="baseFormData.jzrq" disabled />
              </uni-forms-item>
            </uni-forms>

            <el-row>
              <el-col :span="6">
                <label>相关文件：</label>
              </el-col>
              <el-col :span="18">
                <el-upload class="upload-demo" :action="uploadParam.uploadUrl"
                           :headers="uploadParam.headers" :before-upload="rwBeforeUpload" :on-change="handleChange"
                           :on-error="handleUploadError" :on-success="handleUploadSuccess" :auto-upload="true"
                           :on-remove="removeFile" ref="upload" multiple :file-list="uploadParam.fileList">
                  <el-button slot="trigger" ref="uploadInput" size="small">选择文件</el-button>
                </el-upload>
              </el-col>
            </el-row>
          </view>

          <el-row>
            <el-col :span="6">
              <label>下达内容：</label>
            </el-col>
            <el-col>
              <uni-easyinput autoHeight type="textarea" disabled v-model="baseFormData.xdnr"/>
            </el-col>
          </el-row>
          <el-row v-for="option in parentOptions">
            <el-col :span="6">
              <label>{{option.level+'意见'}}：</label>
            </el-col>
            <el-col>
              <uni-easyinput autoHeight type="textarea" disabled v-model="option.spyj"/>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <label>{{option.level+'审批意见'}}：</label>
            </el-col>
            <el-col>
              <uni-easyinput  v-show="option.spStatus==1"  autoHeight disabled  type="textarea"  v-model="spyj"/>
              <uni-easyinput  v-show="option.spStatus==0"  autoHeight  type="textarea"  v-model="spyj"/>
            </el-col>
          </el-row>
          <div v-if="baseFormData.sffk==1" class="box" style="border: none">
            <el-row>
              <label>反馈内容：</label>
              <el-upload class="upload-demo" :action="fkUploadParam.uploadUrl" :headers="fkUploadParam.headers"
                         :before-upload="rwBeforeUpload" :on-change="fkHandleChange" :on-error="handleUploadError"
                         :on-success="handleUploadSuccess" :auto-upload="false" ref="fkUpload" multiple
                         :file-list="fkUploadParam.fileList"
                         :on-remove="fkRemoveFile"
              >
                <el-button :disabled="option.fkzt == 3" slot="trigger" type="primary" icon="el-icon-upload" size="small">上传</el-button>
              </el-upload>
            </el-row>
            <div>
              <uni-easyinput  :disabled="option.fkzt == 3"  autoHeight  type="textarea"  v-model="fknr"/>
            </div>
          </div>
          <view  v-if="isSjy">
            <uni-section title="下达目标" type="line">
              <view v-if="!sfsp" style="margin-left: 50rpx;height: 200rpx;">
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="checkTranUsers">
                  <el-checkbox v-for="user in tranUsers" :label="user.userId" :key="user.userId">{{user.nickName}}</el-checkbox>
                </el-checkbox-group>
              </view>
              <view v-if="sfsp"  style="margin-left: 50rpx;height: 200rpx;">
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="checkTranUsers">
                  <el-checkbox class="readonly" v-for="user in tranUsers" :label="user.userId" :key="user.userId">{{user.nickName}}</el-checkbox>
                </el-checkbox-group>
              </view>
            </uni-section>
          </view>
          <view v-else>
            <uni-section title="下达目标" type="line">
              <view v-if="!sfsp" style="margin-left: 50rpx;height: 200rpx;">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                  <el-checkbox v-for="city in cities" :label="city.deptId" :key="city.deptId">{{city.deptName}}</el-checkbox>
                </el-checkbox-group>
              </view>
              <view v-if="sfsp" style="margin-left: 50rpx;height: 200rpx;">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                  <el-checkbox class="readonly" v-for="city in cities" :label="city.deptId" :key="city.deptId">{{city.deptName}}</el-checkbox>
                </el-checkbox-group>
              </view>
            </uni-section>
          </view>
          <view class="action-btn">
            <button style="margin-bottom: 10px" :disabled="sfsp"  @click="submitFrom" class="bg-blue lg round">转达下级</button>
            <button :disabled="option.fkzt == 3" v-loading.fullscreen.lock="submitFkLoading" style="margin-bottom: 10px" @click="submitAppZjxdFk()" class="bg-blue lg round">提交反馈</button>
            <button  style="margin-bottom: 10px" @click="goToNextStep" class="bg-blue lg round">下达基层</button>
            <button  style="margin-bottom: 10px" @click="toList" class="bg-blue lg round">查看人员反馈详情 ></button>
          </view>
        </uni-section>

      </view>
    </view>
    <view v-show="currentStep === 1">
      <view class="container">
        <view class="uni-padding-wrap uni-common-mt">
          <uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" />
        </view>
        <view class="content">
          <view v-if="current === 0">
            <el-tree ref="tree" node-key="id" :data="deptTree" :default-expanded-keys="checkTreeIds"
                     :default-checked-keys="checkTreeIds" show-checkbox :props="defaultProps"
                     @check="check"></el-tree>
          </view>
          <view v-if="current === 1">
            <view class="article">
              <el-checkbox-group v-model="checkList">
                <el-checkbox class="tabClass" v-for="tab in tabList" :label="tab.id"
                             :key="tab.id">{{ tab.name }}
                </el-checkbox>
              </el-checkbox-group>
            </view>
          </view>
        </view>

        <view class="action-btn fixed-bottom">
          <view class="two_button">
            <button @click="goToBackStep" type="default" plain="true" class="round"
                    style="width: 45%;">上一步</button>
            <!-- <button @click="submit()" class="bg-blue lg round" style="width: 45%;">提交</button> -->
            <el-button v-loading.fullscreen.lock="submitLoading" @click="submit()" type="primary" round
                       style="width: 45%;">下达任务</el-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
	import {
		getDicts
	} from "@/api/system/dict/data";
  import {
    tranAppXdrw,
    getAppZjxdRwbInfo,
    addAppZjxdwj,
    getAppCityLevel, tranAppXdrwToUser, submitAppZjxdFk
  } from "@/api/system/yjgl";
	import config from '@/config';
	import {
		getToken,
		getUsername,
    getDeptId
	} from '@/utils/auth'
  import {getDepartmentList, getUserLabelList} from "@/api/system/xdwj";

	export default {
		data() {
			return {
        current: 0,
        items: ['部门', '标签'],
        checkList: [], //选中的tab
        tabList: [],
        checkTreeIds: [], //选中的部门ID
        deptTree: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        currentStep: 0, // 当前步骤，初始为0
        steps: [ // 步骤列表
          {
            title: '维护信息'
          },
          {
            title: '选择部门/标签'
          }
        ],
				isIndeterminate: true,
				checkAll: false,
				checkedCities: [],
				checkTranUsers: [],
				cityOptions: [],
			    cities:[],

				sid: "",
        submitFkLoading: false,
				submitLoading: false,
				// 基础表单数据
				baseFormData: {
					sid: "",
					sxbt: "",
					sxxz: "",
					jjcd: "",
					jgsj: "1",
					sffk: "",
					jzrq: "",
					rwlx: "",
				},
        option:[],
        parentOptions:[],
        tranUsers:[],
				spyj: "",
				sfsp: null,
        isSjy: null,
				sxxzDict: [],
				sxlxDict: [],
				sffkDict: [],
				jjcdDict: [],
				jgsjDict: [{
						value: "0.5",
						text: "半小时"
					},
					{
						value: "1",
						text: "1小时"
					},
					{
						value: "2",
						text: "2小时"
					},
					{
						value: "3",
						text: "3小时"
					},
					{
						value: "5",
						text: "5小时"
					},
					{
						value: "8",
						text: "8小时"
					},
					{
						value: "12",
						text: "12小时"
					},
					{
						value: "24",
						text: "24小时"
					},
					{
						value: "48",
						text: "48小时"
					}
				],
				uploadParam: {
					// 上传的图片服务器地址
					uploadUrl: config.baseUrl + "/common/upload",
					headers: {
						Authorization: "Bearer " + getToken()
					},
					fileType: [
						["doc", "xls", "ppt", "txt", "pdf"],
					],
					fileList: [],
					showFileList: []
				},
        fkUploadParam: {
          // 上传的图片服务器地址
          uploadUrl: config.baseUrl + "/common/upload",
          headers: {
            Authorization: "Bearer " + getToken()
          },
          fileType: [
            ["doc", "xls", "ppt", "txt", "pdf"],
          ],
          fileList: [],
          showFileList: []
        },
        fknr:""
			}
		},
		onLoad(options) {
			this.sid = options.sid;
		},
		created() {
			// 字典翻译
			getDicts("sxxz").then(response => {
				for (let item of response.data) {
					this.sxxzDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});

      // 字典翻译
			getDicts("sxlx").then(response => {
				for (let item of response.data) {
					this.sxlxDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			getDicts("sffk").then(response => {
				for (let item of response.data) {
					this.sffkDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			getDicts("jjcd").then(response => {
				for (let item of response.data) {
					this.jjcdDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			this.getAppCityLevel();
			this.getInfo();
      getDepartmentList({deptId:getDeptId()}).then(res => {
        this.deptTree = res.data;
      });
      getUserLabelList({}).then(res => {
        this.tabList = res.data;
      });
		},
		methods: {
      goToBackStep() {
        this.currentStep--;
      },
      submitAppZjxdFk() {
        this.submitFkLoading = true;
        this.$refs.fkUpload.submit();
        let data = {
          "fjbs": this.fkUploadParam.fileList,
          "sid": this.option.id,
          "fknr":this.fknr
        }
        this.submitFkLoading = false;
        console.log(data);
        setTimeout(res => {
          submitAppZjxdFk(data).then(res => {
            if (res.code == 200) {
              this.submitFkLoading = false;
              uni.switchTab({
                url: '/pages/index',
              })
            } else {
              this.$modal.msgError(res.msg);
            }
          })
        }, 2000)
      },
      check() {
        let selectDepts = this.$refs.tree.getCheckedNodes();
        let deptIds = selectDepts.map(d => d.id);
        deptIds = selectDepts.filter(dept => !deptIds.includes(dept.parentId));
        this.checkTreeIds = deptIds.map(d => d.id)
      },
      submit() {
        this.submitLoading = true
        this.baseFormData.rwlx = "2";
        const checkTabIds = this.checkList.map(String);
        const data = {
          'username': getUsername(),
          'zjxdRwb': this.baseFormData,
          'fjbs': this.uploadParam.fileList,
          'deptIds': this.checkTreeIds,
          'tabIds': checkTabIds,
          'ly': '2',
          'spyj': this.spyj,
          "workid": this.workid
        }
        console.log(data)
        tranAppXdrwToUser(data).then(res => {
          this.submitLoading = false;
          this.$modal.msgSuccess("添加成功");
          uni.navigateBack()
        }).catch(err => {
          console.log('err', err);
          this.$modal.msgError("添加失败");
          this.submitLoading = false;
        });
      },
      onClickItem(e) {
        if (this.current != e.currentIndex) {
          this.current = e.currentIndex;
        }
      },
      toList() {
        this.$tab.navigateTo("/pages/home/step/ckUserList?sid=" + this.sid);
      },
      goToNextStep() {
        if (this.currentStep === 0) {
          console.log(this.baseFormData)
          this.currentStep++; // 增加当前步骤索引
        }
      },
			getInfo(){
				getAppZjxdRwbInfo({sid: this.sid, username: getUsername() }).then(res => {
					this.sfsp = res.data.sfsp;
					this.checkTranUsers = res.data.checkTranUsers;
          this.isSjy = res.data.isSjy;
          this.option = res.data.option;
          if (this.option){
            this.fknr = this.option.fknr;
          }
          this.spyj = res.data.option.spyj;
					this.checkedCities = res.data.deptIds;
					// this.baseFormData.sid = res.data.sid;
					// this.baseFormData.sxbt = res.data.sxbt;
					// this.baseFormData.sxxz = res.data.sxxz;
					// this.baseFormData.jjcd = res.data.jjcd;
					// this.baseFormData.sffk = res.data.sffk;
					// this.baseFormData.jzrq = res.data.jzrq;
					// this.baseFormData.sxbt = res.data.sxbt;
					// this.baseFormData.xdnr = res.data.xdnr;
          this.baseFormData = res.data;
          this.parentOptions = res.data.parentOptions;
          this.uploadParam.fileList = res.data.fjbs;
					this.tranUsers = res.data.tranUsers;
					res.data.fjbs.forEach(item =>{
						this.uploadParam.showFileList.push({
							url : item.wjdz,
							name : item.wjmc
						})
					});
					console.log(this.uploadParam.fileList)
				});
			},
			getAppCityLevel(){
			  getAppCityLevel({username:  getUsername()}).then(res=>{
				if (res.code==200){
				  this.cityOptions = res.data;
				  this.cities = this.cityOptions;
				}
			  })
			},
			handleCheckAllChange(val) {
			  this.checkedCities = val ? this.cityOptions.map(m=>m.deptId) : [];
			  this.isIndeterminate = false;
			},
			handleCheckedCitiesChange(value) {
			  let checkedCount = value.length;
			  this.checkAll = checkedCount === this.cities.length;
			  this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
			},
      handleCheckedCitiesChange1(value) {
			  let checkedCount = value.length;
			  this.checkAll = checkedCount === this.tranUsers.length;
			  this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
			},
			goBack() {
				uni.navigateBack();
			},
			submitFrom() {
        if (this.isSjy) {

          if (this.checkTranUsers.length == 0) {
            this.$modal.msgError("请选择转达部门");
            return false;
          }
        } else {

          if (this.checkedCities.length == 0) {
            this.$modal.msgError("请选择转达部门");
            return false;
          }
        }
				this.baseFormData.rwlx = "2";
				console.log(this.baseFormData)
				let data = {
					"username": getUsername(),
					"zjxdRwb": this.baseFormData,
					"fjbs": this.uploadParam.fileList,
					"deptIds": this.checkedCities,
					"spyj":this.spyj,
					"userIds":this.checkTranUsers,
				  }
				console.log(data)
				tranAppXdrw(data).then(res => {
				  this.submitLoading = false;
				  this.$modal.msgSuccess("转发成功");
				  uni.navigateBack();
				}).catch(err => {
					console.log('err', err);
					this.$modal.msgError("转发失败");
					this.submitLoading = false;
				});
			},
			changeSxxzDict(e) {
				this.baseFormData.sxxz = e
			},
      changeSxlxDict(e) {
				this.baseFormData.sxlx = e
			},
			changeJjcdDict(e) {
				this.baseFormData.jjcd = e.detail.value
			},
			changeJgsjDict(e) {
				this.baseFormData.jgsj = e
			},
			changeSffkDict(e) {
				this.baseFormData.sffk = e.detail.value
			},
			submitUpload() {
				this.$refs.upload.submit();
			},
			// 上传失败
			handleUploadError(err) {
				console.log("上传失败...")
				this.$modal.msgError("上传文件失败，请重试");
				this.$modal.closeLoading();
			},
			rwBeforeUpload(file) {
				console.log("上传前...");
			},
			handleChange(file, fileList) {
				this.uploadParam.fileList = fileList;
			},
      fkHandleChange(file, fileList) {
				this.fkUploadParam.fileList = fileList;
			},
			// 上传成功回调
			handleUploadSuccess(res, file) {
				console.log("上传成功...");
			},
			// 移除附件操作
			removeFile(file, fileList) {
				this.uploadParam.fileList = fileList;
			},

      fkRemoveFile(file, fileList) {
        this.fkUploadParam.fileList = fileList;
      }
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f6f7;
	}

	.container {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.fixed-bottom {
		position: fixed;
		bottom: var(--window-bottom);
		bottom: 0;
		width: 95%;
		margin-bottom: 20rpx;
		z-index: 999;
	}

	.two_button {
		display: flex;
	}

	.article {
		background-color: white;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.tabClass {
		font-size: 80rpx;
		margin-left: 40rpx;
		margin-right: 400rpx;
	}

	::v-deep .is-disabled {
		color: black !important;
	}

	.el-checkbox.readonly {
	  pointer-events: none;
	  cursor: default;
	}

	.el-checkbox.readonly .el-checkbox__input {
	  display: none;
	}

	.el-checkbox.readonly .el-checkbox__label {
	  color: #606266; /* 根据需要可以更改文本颜色 */
	}

</style>
